<template>
  <el-date-picker
    v-model="tempTimeVal"
    type="daterange"
    align="right"
    unlink-panels
    value-format="yyyy-MM-dd"
    :range-separator="separator"
    :start-placeholder="startPlaceholder"
    :end-placeholder="endPlaceholder"
    :picker-options="pickerOptions"
    @change="handleChange"
    :size="size"
  ></el-date-picker>
</template>

<script>
import i18n from '@/lang/index'
export default {
  name: 'DateSelect',
  props: {
    separator: {
      type: String,
      default: i18n.t('dateSelector.to'),
    },
    startPlaceholder: {
      type: String,
      default: i18n.t('dateSelector.beginDate'),
    },
    endPlaceholder: {
      type: String,
      default: i18n.t('dateSelector.endDate'),
    },
    // 默认展示当前月，从1号开始
    currentMonth: {
      type: Boolean,
      default: false,
    },
    size: {
      type: String,
      default: 'small',
    },
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: i18n.t('dateSelector.latestWeek'),
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: i18n.t('dateSelector.latestMonth'),
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: i18n.t('dateSelector.latestThreeMonth'),
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            },
          },
        ],
      },
      tempTimeVal: this.tempTimeVal,
    }
  },
  created() {
    // 默认选中当前月，从一号开始,月底结束
    if (this.currentMonth) {
      const now = new Date()
      let firstDayOfNextMonth
      if (now.getMonth() === 11) {
        firstDayOfNextMonth = new Date(now.getFullYear() + 1 + '-01-01')
      } else {
        firstDayOfNextMonth = new Date(
          now.getFullYear() + '-' + (now.getMonth() + 2) + '-01'
        )
      }
      const lastDayOfMonthObj = new Date(firstDayOfNextMonth.getTime() - 3600)
      const lastDayOfMonth =
        lastDayOfMonthObj.getFullYear() +
        '-' +
        (lastDayOfMonthObj.getMonth() + 1) +
        '-' +
        lastDayOfMonthObj.getDate()
      const firstDayOfMonth =
        now.getFullYear() + '-' + (now.getMonth() + 1) + '-01'
      this.tempTimeVal = [firstDayOfMonth, lastDayOfMonth]
      this.handleChange(this.tempTimeVal)
    }
  },
  methods: {
    handleChange(e) {
      this.$emit('input', e)
    },
  },
}
</script>
